<route lang="json5">
{
layout: 'tabbar',
style: {
navigationStyle: 'custom',
navigationBarTitleText: '课程预约',
},
}
</route>

<script lang="ts" setup>
import { getDate, getCourseList } from "@/api/login";

// 屏幕安全区域逻辑（保持不变）
let safeAreaInsets: UniApp.SafeAreaInsets | null = null
let systemInfo: UniApp.GetSystemInfoResult | UniApp.WindowInfo = {} as any
// #ifdef MP-WEIXIN
systemInfo = uni.getWindowInfo()
safeAreaInsets = systemInfo.safeArea
  ? {
    top: systemInfo.safeArea.top,
    right: systemInfo.windowWidth - systemInfo.safeArea.right,
    bottom: systemInfo.windowHeight - systemInfo.safeArea.bottom,
    left: systemInfo.safeArea.left,
  }
  : null
// #endif
// #ifndef MP-WEIXIN
systemInfo = uni.getSystemInfoSync()
safeAreaInsets = systemInfo.safeAreaInsets
// #endif

// 课程数据类型定义（保持不变）
interface Course {
  id: number;
  fitnessDate: string;
  name: string;
  maxPeople: number;
  startTime: string;
  endTime: string;
  createTime: string;
  createBy: number;
  updateTime: string;
  updateBy: number;
  isDeleted: number;
  currentPeople?: number;
  coachName?: string;
  reservedUsers?: { avatar: string }[];
}

// 响应式数据（保持不变）
const currentTab = ref<'group' | 'private'>('group')
const dateList = ref<any[]>([])
const currentDateIndex = ref(0)
const courseList = ref<Course[]>([])
const loading = ref(false)
const backgroundImage = ref('')
const hasBackground = ref(false)

// 教练列表数据（保持不变）
const privateCoaches = ref([
  { name: '连', avatar: '/static/coach1.png', status: 'available' },
  { name: '刘杰', avatar: '/static/coach1.png', status: 'available' },
  { name: '王聪', avatar: '/static/coach1.png', status: 'available' },
  { name: '白雪皓', avatar: '/static/coach1.png', status: 'available' },
  { name: '段勇', avatar: '/static/coach1.png', status: 'available' },
  { name: '宋浩然', avatar: '/static/coach1.png', status: 'unavailable' },
])

// Tab 切换、数据请求、预约逻辑（保持不变）
function switchTab(tab: 'group' | 'private') {
  currentTab.value = tab
  if (tab === 'private') {
    console.log('切换到私教预约页面')
  }
}

// 获取日期列表和背景图数据
const fetchDateList = () => {
  getDate().then((response) => {
    if (response.code === 200) {
      dateList.value = response.data.days
      // 判断接口是否返回背景图
      if (response.data.background && response.data.background.trim() !== "") {
        backgroundImage.value = response.data.background
        hasBackground.value = true
      } else {
        hasBackground.value = false // 无有效背景图，切换纯色
      }
      const todayIndex = response.data.days.findIndex(item => item.IsToday)
      if (todayIndex !== -1) {
        currentDateIndex.value = todayIndex
        courseList.value = response.data.details
      }
    } else {
      console.error('获取日期列表失败:', response.msg)
      hasBackground.value = false // 接口失败时用纯色
    }
  }).catch((error) => {
    console.error('获取日期列表异常:', error)
    hasBackground.value = false // 异常时用纯色
  })
}

// 获取课程列表数据（使用小驼峰参数）
const fetchCourseList = (date: number) => {
  loading.value = true
  getCourseList({
    fitnessDate: date,
    isDeleted: 0
  }).then((response) => {
    loading.value = false
    if (response.code === 200) {
      courseList.value = response.data
    } else {
      console.error('获取课程列表失败:', response.msg)
      courseList.value = []
    }
  }).catch((error) => {
    loading.value = false
    console.error('课程列表请求异常:', error)
    courseList.value = []
  })
}

// 日期切换时更新课程列表
watch(currentDateIndex, (newIndex) => {
  if (dateList.value.length > 0) {
    fetchCourseList(newIndex)
  }
})

// 处理课程预约
function handleReservation(course: Course) {
  console.log('预约课程:', course)
  uni.showModal({
    title: '预约确认',
    content: `确定要预约${course.name}（${course.startTime}-${course.endTime}）吗？`,
    success: (res) => {
      if (res.confirm) {
        // 调用预约接口
      }
    }
  })
}

// 处理私教购买
function handleBuy(coach: any) {
  console.log('购买私教课程:', coach.name)
}

// 动态计算容器样式
const containerStyle = computed(() => {
  const baseStyle = {
    marginTop: safeAreaInsets?.top + 'px',
  }
  if (hasBackground.value) {
    return {
      ...baseStyle,
      background: `url(${backgroundImage.value}) no-repeat center/cover`,
    }
  } else {
    return {
      ...baseStyle,
      'background-color': '#f8e9d6', // fallback 纯色
    }
  }
})

// 动态计算课程卡片背景样式
const courseCardBgStyle = computed(() => {
  if (hasBackground.value) {
    return {
      backgroundImage: `url(${backgroundImage.value})`,
      backgroundSize: 'cover',
    }
  } else {
    return {
      'background-color': '#f0b9a8', // 卡片 fallback 纯色
    }
  }
})

onLoad(() => {
  console.log('课程预约页面加载')
  fetchDateList()
})
</script>

<template>
  <view class="container" :style="containerStyle">
    <!-- 顶部导航栏（保持不变） -->
    <view class="top-bar flex flex-col items-center px-4 py-2">
      <view class="title mt-1 font-bold mb-2">句芒综合训练馆</view>
      <view class="tab-group flex border border-[#b32414] rounded-md overflow-hidden">
        <view
          class="tab-item"
          :class="{ active: currentTab === 'group' }"
          @click="switchTab('group')"
        >
          精品团课
        </view>
        <view
          class="tab-item"
          :class="{ active: currentTab === 'private' }"
          @click="switchTab('private')"
        >
          私教预约
        </view>
      </view>
    </view>

    <!-- 日期切换栏（保持不变） -->
    <view v-if="currentTab === 'group'" class="date-bar flex items-center justify-around py-2">
      <view
        v-for="(dateItem, index) in dateList"
        :key="index"
        class="date-item flex flex-col items-center"
        @click="currentDateIndex = index"
      >
        <text class="date-number text-xl font-bold" :class="{ active: index === currentDateIndex }">
          {{ dateItem.Date }}
        </text>
        <text class="date-label text-sm" :class="{ active: index === currentDateIndex }">
          {{ dateItem.IsToday ? '今日' : dateItem.Week }}
        </text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content px-2 py-2">
      <!-- 精品团课内容 -->
      <view v-if="currentTab === 'group'">
<!--        <view class="filter-bar mb-4 flex items-center justify-between rounded-lg bg-white p-3 shadow-sm">-->
<!--          <view class="course-type flex items-center">-->
<!--            <text class="mr-1 text-gray-600">全部课程</text>-->
<!--            <text class="text-xs text-gray-400">▼</text>-->
<!--          </view>-->
<!--          <view class="time-slot flex items-center">-->
<!--            <text class="mr-1 text-gray-600">全部时段</text>-->
<!--            <text class="text-xs text-gray-400">▼</text>-->
<!--          </view>-->
<!--        </view>-->

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container flex justify-center py-10">
          <uni-loading type="circle" size="24"></uni-loading>
          <text class="ml-2 text-gray-500">加载中...</text>
        </view>
        <view v-else-if="courseList.length === 0" class="empty-container flex flex-col items-center py-10">
          <image src="/static/empty.png" class="w-20 h-20 mb-2" mode="widthFix"></image>
          <text class="text-gray-500">当前日期暂无课程</text>
        </view>

        <!-- 课程列表（核心调整区域） -->
        <view v-else class="course-list space-y-3">
          <view
            v-for="(course, index) in courseList"
            :key="course.id"
            class="course-card"
            :style="courseCardBgStyle"
          >
            <!-- 上半部分：左右布局（左上信息 + 右上按钮） -->
            <view class="card-top flex">
              <!-- 左上信息区：垂直排列，占比 2/3 -->
              <view class="info-box flex flex-col space-y-1" style="flex: 2;">
                  <text class="text-sm ">{{ course.name }}</text>
                  <text class="text-3xl ">{{ course.startTime }} ~ {{ course.endTime }}</text>
                  <text class="text-sm ">
                    {{ course.currentPeople || 0 }}/{{ course.maxPeople }}人 | 教练：{{ course.coachName || '未知' }}
                  </text>
              </view>
              <!-- 右上按钮区：占比 1/3，按钮上下居中 -->
              <view class="btn-wrap flex justify-center items-center" style="flex: 1;">
                <button
                  class="reserve-btn rounded-md px-10 py-2 text-sm text-white hover:bg-[#9a1f10]"
                  :disabled="(course.currentPeople || 0) >= course.maxPeople"
                  @click="handleReservation(course)"
                >
                  {{ (course.currentPeople || 0) >= course.maxPeople ? '已满' : '预约' }}
                </button>
              </view>
            </view>

            <!-- 浅色虚线分隔（新增，分隔上下部分） -->
            <view class="divider my-2"></view>

            <!-- 最下方：已预约用户头像区（保留功能） -->
            <view class="avatar-box flex flex-wrap">
              <image
                v-for="(user, uIndex) in course.reservedUsers"
                :key="uIndex"
                :src="user.avatar"
                class="mr-1 h-7 w-7 rounded-full border border-white"
                mode="aspectFill"
              />
              <!-- 无预约时占位（可选，保证布局高度） -->
              <view class="placeholder" v-if="!(course.reservedUsers && course.reservedUsers.length > 0)"></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 私教预约内容（保持不变） -->
      <view v-else>
        <view class="coach-list">
          <view
            v-for="(coach, index) in privateCoaches"
            :key="index"
            class="coach-item flex items-center justify-between border-b py-2"
          >
            <view class="flex items-center">
              <image
                :src="coach.avatar"
                class="avatar mr-2 h-12 w-12 rounded-full border border-white"
                mode="aspectFill"
              />
              <text class="coach-name text-lg font-bold text-[#333]">{{ coach.name }}</text>
            </view>
            <view class="button-group">
              <button
                v-if="coach.status === 'available'"
                class="buy-btn rounded-md bg-[#b32414] text-sm text-white px-4 py-2 hover:bg-[#9a1f10]"
                @click="handleBuy(coach)"
              >
                购买
              </button>
              <button v-else class="disabled-btn rounded-md bg-gray-300 text-white px-4 py-2">
                暂无课程
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped>
/* 基础样式（保持不变） */
.container {
  min-height: 100vh;
}

/* 顶部导航栏（保持不变） */
.top-bar {
  background-color: rgba(245, 230, 216, 0.9);
}
.title {
  color: #333;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  letter-spacing: 1px;
}

/* Tab 切换按钮（保持不变） */
.tab-group {
  /* 保持原有样式，增加黑色边框 */
  border: 1px solid #510f07; /* 黑色边框 */
  border-radius: 4px;
  overflow: hidden;
}
.tab-item {
  flex: 1;
  text-align: center;
  padding: 6px 10px;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  font-weight: 600; /* 加粗字体 */
  color: #333; /* 深黑色文字 */
  transition: all 0.3s ease;
}
.tab-item.active {
  background-color: #b32414;
  color: #fff;
}

/* 日期栏（保持不变） */
.date-bar {
  background-color: rgba(245, 230, 216, 0.9);
}
.date-item {
  color: #333;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}
.date-number.active {
  color: #b32414;
  font-weight: bold;
}
.date-label.active {
  color: #b32414;
}

/* 内容区域（保持不变） */
.content {
  margin: 8px;
  border-radius: 8px;
  min-height: calc(100vh - 200px);
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}

/* 加载 & 空状态（保持不变） */
.loading-container {
  align-items: center;
}
.empty-container {
  align-items: center;
  color: #999;
}

/* 课程卡片核心样式调整 */
.course-card {
  border-radius: 4px;
  overflow: hidden;
  padding: 4px;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  background: linear-gradient(to right, #b34f44, #fab7ad); /* 从左到右的渐变 */
}
.course-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 上半部分布局：左右分散对齐 */
.card-top {
  align-items: stretch; /* 让信息和按钮分别对齐顶部 */
  gap: 10px;
}
/* 按钮外层容器，用于居中按钮 */
.btn-wrap {
  /* 清除默认的 margin，避免影响布局 */
  margin: 0;
}
.info-box {
  position: relative;
  box-sizing: border-box;
  font-family: sans-serif;
  flex: 2;
  padding: 10px;

  background:
    linear-gradient(#fff, #fff) left top,
    linear-gradient(#fff, #fff) left top,
    linear-gradient(#fff, #fff) right top,
    linear-gradient(#fff, #fff) right top,
    linear-gradient(#fff, #fff) left bottom,
    linear-gradient(#fff, #fff) left bottom,
    linear-gradient(#fff, #fff) right bottom,
    linear-gradient(#fff, #fff) right bottom;
  background-repeat: no-repeat;
  background-size: 2px 20px, 20px 2px;
  color: #fff;
}

/* 右上按钮样式 */
.reserve-btn {
  white-space: nowrap;
  transition: background-color 0.3s ease;
  align-self: center; /* 确保按钮自身垂直居中 */
  border-radius: 36px;
  background-color: #b32414;
}

.reserve-btn:disabled {
  background-color: #999 !important;
  opacity: 0.8;
  cursor: not-allowed;
}

/* 虚线分隔（新增） */
.divider {
  width: 100%;
  border-top: 1px dashed #eee; /* 直接使用虚线边框 */
  margin: 4px 0; /* 调整上下间距 */
}

/* 最下方头像区样式 */
.avatar-box {
  min-height: 40px; /* 保证无头像时也有高度 */
  align-items: flex-start;
}
.placeholder {
  width: 40px;
  height: 40px;
  visibility: hidden;
}

/* 私教列表（保持不变） */
.coach-list {
  padding: 10px;
}
.coach-item {
  background-color: rgba(255, 255, 255, 0.9);
  transition: background-color 0.3s ease;
}
.coach-item:hover {
  background-color: #fafafa;
}
.avatar {
  border: 1px solid #eee;
}
.coach-name {
  color: #333;
}
.buy-btn, .disabled-btn {
  transition: background-color 0.3s ease;
}
</style>
